var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var utils = require('./utils');
var noOp = utils.noOp;

var GOOGLE_CLIENT_ID = {
  dev : "616440645031-1j6d82i97a1jflp9p5a93n5cdf6kcefj.apps.googleusercontent.com",
  prod : "616440645031.apps.googleusercontent.com"
};
var GOOGLE_CLIENT_SECRET = {
  dev : "BF7izM-P4E9cohhTMKyLxlRm",
  prod : '1En8Yn5gLrWDV-zbfQFtzfEk'
};
var GOOGLE_CALLBACK_URL = {
  dev: "http://localhost:3000/auth/google/oauth2callback",
  prod: "http://www.spargame.com:3000/auth/google/oauth2callback"
};

exports.initSignups = function(env, models) {
 passport.use(new GoogleStrategy({
   clientID: GOOGLE_CLIENT_ID[env],
   clientSecret: GOOGLE_CLIENT_SECRET[env],
   callbackURL: GOOGLE_CALLBACK_URL[env],
 },
 function(accessToken, refreshToken, profile, done) {
   models.Player.findOne({where: { remoteId: profile.id }}, function(err, player) {
     if (player) {
       return setRemoteAvatar(player, profile, done);
     } else {
       models.Player.create({
         remoteId: profile.id, name: profile._json.name },
         function(err, player){
           if (err) { return done(err); }
           return setRemoteAvatar(player, profile, done);
         });
     }
   });
 }));
};

function setRemoteAvatar(player, profile, done) {
  player.setMetadata([{key: 'remoteAvatar', value: profile._json.picture || ""}], function(){
    return done(null, player);
  });
}